<?php

function get_last_record_time()
{/*{{{*/
    $coin_market = db_simple_query_first('coin_market', ['record_time <=' => datetime()], 'order by id desc');

    return $coin_market['record_time'];
}/*}}}*/

function get_last_coinmarket($limit)
{/*{{{*/
    $last_record_time = get_last_record_time();

    $option_sql = 'order by rank';

    if ($limit) {
        $option_sql .= " limit $limit";
    }

    return db_simple_query('coin_market', ['record_time' => $last_record_time], $option_sql);
}/*}}}*/

function get_24h_volume_cny_ratio()
{/*{{{*/
    $last_record_time = get_last_record_time();

    $option_sql = 'order by 24h_volume_cny desc';

    $coinmarkets = db_simple_query('coin_market', ['record_time' => $last_record_time, '24h_volume_cny <>' => 0], $option_sql);

    $total_volume = db_query_value('total', 'select sum(24h_volume_cny) as total from coin_market where record_time = :record_time', [':record_time' => $last_record_time]);

    $res = [];

    foreach ($coinmarkets as $n => $coinmarket) {
        $ratio = round($coinmarket['24h_volume_cny'] * 100 / $total_volume, 2);

        if ($ratio) {
            $res[] = [
                'lower_case_name' => $coinmarket['lower_case_name'],
                'name' => $coinmarket['name'],
                'symbol' => $coinmarket['symbol'],
                '24h_volume_cny' => $coinmarket['24h_volume_cny'],
                'ratio' => round($coinmarket['24h_volume_cny'] * 100 / $total_volume, 4),
                'rank' => $coinmarket['rank'],
                'volume_rank_rank' => $coinmarket['rank'] - $n - 1,
            ];
        }
    }

    return $res;
}/*}}}*/

function get_percent_change_1h($limit, $order)
{/*{{{*/
    $last_record_time = get_last_record_time();

    $option_sql = "order by percent_change_1h $order";

    if ($limit) {
        $option_sql .= " limit $limit";
    }

    return db_simple_query('coin_market', ['record_time' => $last_record_time], $option_sql);
}/*}}}*/

function get_percent_change_24h($limit, $order)
{/*{{{*/
    $last_record_time = get_last_record_time();

    $option_sql = "order by percent_change_24h $order";

    if ($limit) {
        $option_sql .= " limit $limit";
    }

    return db_simple_query('coin_market', ['record_time' => $last_record_time], $option_sql);
}/*}}}*/
